package com.example.service;

import com.example.entity.RecomHistory;
import com.example.mapper.RecomHistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RecomService {
    @Autowired
    private RecomHistoryRepository recomHistoryRepository;


    public List<String> getRecommendations(Long userId) {
        List<RecomHistory> histories = recomHistoryRepository.findByUserId(userId);
        return generateRecommendations(histories);
    }

    private List<String> generateRecommendations(List<RecomHistory> histories) {
        Map<String, Integer> frequencyMap = new HashMap<>();
        for (RecomHistory history : histories) {
            String searchTerm = history.getSearchTerm();
            frequencyMap.put(searchTerm, frequencyMap.getOrDefault(searchTerm, 0) + 1);
        }

        return frequencyMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .limit(5)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }
}



